import React, { useEffect } from 'react';
import { Button, Dropdown, Icon, Menu } from 'antd';
import { debounce } from 'lodash';
import cn from 'classnames';
import styles from './style.less';

const Pagination = props => {
    const {
        loading = false,
        current: originCurrent = 1,
        total: originTotal = 0,
        pageSize: originPageSize = 10,
        pageSizes = [10, 20, 50, 100, 200],
        onChange,
        filters,
        sorter
    } = props;

    const current = Number(originCurrent);
    const total = Number(originTotal);
    const pageSize = Number(originPageSize);
    const [pageSizeState, setPageSizeState] = React.useState(originPageSize || 10);

    useEffect(() => {
        if (originPageSize && pageSizeState !== originPageSize) {
            setPageSizeState(originPageSize)
        }
    }, [originPageSize])

    const ref = React.useRef();
    const pageSizeRef = React.useRef();

    const totalPages = React.useMemo(
        () => (total % pageSize === 0 ? parseInt(total / pageSize, 10) : parseInt(total / pageSize, 10) + 1) || 1,
        [total, pageSize]
    );

    const pagerList = React.useMemo(() => [...new Array(totalPages)].map((_, index) => index + 1), [totalPages]);
    const [isPageSizesVisible, setPageSizeVisible] = React.useState(false);
    const handleSelectPageSize = value => () => {
        setPageSizeVisible(false);
        setPageSizeState(Number(value));
        onChange({ pageSize: Number(value), current: 1 }, filters, sorter);
    };

    const handleSelectPage = item => () => {
        onChange({ pageSize: Number(pageSizeState), current: Number(item) }, filters, sorter);
    };

    const handlePrev = debounce(() => {
        const currentPage = current === 1 ? 1 : current - 1;
        onChange({ pageSize: Number(pageSizeState), current: currentPage }, filters, sorter);
    }, 300);

    const handleNext = debounce(() => {
        const currentPage = current === totalPages ? totalPages : current + 1;
        onChange({ pageSize: Number(pageSizeState), current: currentPage }, filters, sorter);
    }, 300);

    const pages = (
        <Menu className={styles.menu}>
            {pagerList.map(item => (
                <Menu.Item
                    key={item}
                    className={`${Number(item) === current ? 'ant-dropdown-menu-item-active' : ''}`}
                    onClick={handleSelectPage(item)}
                >
                    {item}
                </Menu.Item>
            ))}
        </Menu>
    );

    const pageSizesMenu = (
        <Menu className={styles.menu}>
            {pageSizes.map(item => (
                <Menu.Item
                    key={item}
                    className={`${Number(item) === pageSize ? 'ant-dropdown-menu-item-active' : ''}`}
                    onClick={handleSelectPageSize(item)}
                >
                    {`${item} 条/页`}
                </Menu.Item>
            ))}
        </Menu>
    );
    return (
        <div
            className={cn(styles.pagination, { [styles.disabled]: loading })}
            style={{ display: total === 0 ? 'none' : 'flex' }}
        >
            <div className={styles.total}>{`共 ${total} 条`}</div>
            <div ref={pageSizeRef}>
                <Dropdown
                    visible={isPageSizesVisible}
                    onVisibleChange={val => setPageSizeVisible(val)}
                    placement="topLeft"
                    overlay={pageSizesMenu}
                    getPopupContainer={dom => (pageSizeRef.current.appendChild ? pageSizeRef.current : dom)}
                    trigger={['click']}
                    overlayStyle={{
                        border: '1px solid #ddd',
                        borderRadius: 4
                    }}
                >
                    <Button className={styles.pageSize}>
                        {`${pageSize} 条/页`} <Icon rotate={isPageSizesVisible ? 180 : 0} type="down"></Icon>
                    </Button>
                </Dropdown>
            </div>
            <div ref={ref}>
                <Button.Group className={styles.pageBtn}>
                    <Button
                        icon="left"
                        className={styles.prevBtn}
                        onClick={handlePrev}
                        disabled={current === 1 || loading === true}
                    />
                    <Dropdown
                        placement="topLeft"
                        overlay={pages}
                        trigger={['click']}
                        getPopupContainer={dom => (ref.current.appendChild ? ref.current : dom)}
                        overlayStyle={{
                            maxHeight: 160,
                            overflowY: pagerList.length > 5 ? 'scroll' : 'hidden',
                            border: '1px solid #ddd',
                            borderRadius: 4
                        }}
                        disabled={totalPages === 1}
                    >
                        <Button>
                            {/* v46版本的火狐不支持将flex 布局加在button上 */}
                            <div className={styles.pageWrap}>
                                <div>{current}</div>
                                <div className={styles.iconGroup}>
                                    <Icon type="caret-up" />
                                    <Icon type="caret-down" />
                                </div>
                            </div>
                        </Button>
                    </Dropdown>
                    <Button
                        icon="right"
                        className={styles.nextBtn}
                        onClick={handleNext}
                        disabled={current === totalPages || loading === true}
                    />
                </Button.Group>
            </div>
            <div className={styles.totalPage}>{`共 ${totalPages} 页`}</div>
        </div>
    );
};

export default React.memo(Pagination);
